package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.dto.LoginDto;
import com.heima.admin.entity.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.IAdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-08-06
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements IAdUserService {

    //登录
    public ResponseResult login(LoginDto dto) {
        //校验用户名和密码不为空
        if (dto==null|| StringUtils.isEmpty(dto.getName())||StringUtils.isEmpty(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据用户名查询用户
        LambdaQueryWrapper<AdUser> query=new LambdaQueryWrapper<>();
        query.eq(AdUser::getName,dto.getName());
        AdUser one = this.getOne(query);
        //判断用户不存在，提示错误信息
        if (one==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //用户存在，提取用户的盐
        String salt = one.getSalt();
        //使用用户传入的密码+盐生成MD5
        String oldPass= dto.getPassword()+ salt;
        String newPass = DigestUtils.md5DigestAsHex(oldPass.getBytes());
        //用生成的MD5与数据库的MD5进行对比
        if (!newPass.equals(one.getPassword())) {
            //如果对比不一致，说明密码错误，提示用户
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //密码一致，使用JWT生成token
        Map<String, Object> claimMap=new HashMap<>();
        claimMap.put("userId",one.getId());
        claimMap.put("userName",one.getName());
        String token = AppJwtUtil.getToken(claimMap);
        //给前端返回固定格式
        Map<String,Object>resultMap=new HashMap<>();
        //隐藏敏感信息
        one.setPassword(null);
        one.setPhone(null);
        one.setSalt(null);
        resultMap.put("user",one);
        resultMap.put("token",token);
        return ResponseResult.okResult(resultMap);
    }
}
